<template>
  <el-container>
    <vHeadSpace />
    <el-container>
      <vAsideSpace />
      <el-container>
        <el-main class="detailedflow_main">
          <div class="detailedflow_content" id="charts">
            <div>
              <h3 style="font-size: 200%;margin-top: 0">实时流量图</h3>
              <el-button type="primary" size="small" icon="el-icon-arrow-left" @click="prev()" style="margin-right: 15px;margin-bottom: 15px">返回上一页</el-button>
            </div>
          </div>
        </el-main>
        <vFootSpace/>
      </el-container>
    </el-container>
  </el-container>

</template>

<script>
  import axios from "axios";
  export default {
    name: "DetailedFlowChart",
    data() {
      return{
        transfer_data: {},
        timers: [],
        itemlist: [],
        current_timer: '',
        new_data: [],
        hostid: ''
      }
    },
    async mounted() {
      this.transfer_data = this.$route.query;
      // console.log("刚获取");
      console.log(this.$route.query);
      this.hostid = this.transfer_data.hostId
      let result_new = await this.handleFlowChartQuery(this.transfer_data);
      console.log(result_new)
      // 返回的最近历史数据
      let query_result = result_new.datalist

      // console.log("流量图数据");
      // console.log(query_result);

      // 根据类型异步请求最新网络接口数据
      // this.current_timer = setInterval(this.new_data = this.sentNetItemAsyncRequest(this.itemlist),2000)

      if (query_result.length === 0 || query_result[0].data.length === 0) {
        this.$message({
          showClose: true,
          message: '该主机暂无流量图数据',
          type: 'warning'
        });
        for (let i = 0; i < 2; i++) {
          let chartDiv = document.getElementById('charts');
          let flowChart = document.createElement('span');
          flowChart.setAttribute('id', i);
          flowChart.setAttribute('style', "width: 50%;height: 400px; float: left");
          chartDiv.appendChild(flowChart);
          // 在dom加载完成后进行流量图的渲染
          this.$nextTick(() => {
            this.drawEmpty(i);
          })
        }
      }else {
        let divided = [];
        let value = [];

        for (let i = 0; i < query_result.length; i++){
          let init = query_result[i].name.split(":")[0];
          // console.log(init)
          for (let j = i + 1; j < query_result.length; j++) {
            if (query_result[j].name.split(":")[0] === init) {
              value.push(query_result[i]);
              value.push(query_result[j]);
              // console.log(value)
              divided.push(value);
            }
          }
        }
        divided = divided[0];
        for (let i = 0; i < divided.length; i++) {
          // 网络接口的监控项id
          this.itemlist.push(divided[i].itemid)
        }
        // 查询网络流量接口最新值
        var _this = this
          if (this.current_timer != '') {//判断计时器是否为空
              clearInterval(this.current_timer);
              this.current_timer = '';
          }
          this.current_timer = setInterval(()=>{
                  _this.setAsynInterval()
              }
          , 3000);

        // console.log('items:',this.itemlist)
        // 动态添加流量图容器
        for (let i = 0; i < divided.length; i++) {
          let timer = null; // 为每个流量图新增一个timer
          let chartDiv = document.getElementById('charts');
          let flowChart = document.createElement('span');
          flowChart.setAttribute('id', divided[i].name);
          flowChart.setAttribute('style', "width: 50%;height: 400px; float: left");
          chartDiv.appendChild(flowChart);
          this.timers.push(timer);
          // 在dom加载完成后进行流量图的渲染
          this.$nextTick(() => {
            this.drawLine(divided[i], i);
          })
        }
      }

    },
    methods:{
      /*
      * 当无流量图数据时，画空图
      * */
      drawEmpty(i) {
        let myChart = this.$echarts.init(document.getElementById(i));
        let option = {
          title: {
            text: "empty",
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#283b56'
              }
            }
          },
          toolbox: {
            show: true,
            feature: {
              dataView: {readOnly: false},
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: true,
            data: (function () {
              var now = new Date();
              var res = [];
              var len = 10;
              while (len--) {
                res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''));
                now = new Date(now - 180000);
              }
              return res;
            })()
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [],
            type: 'line'
          }]
        };
        myChart.setOption(option, true);
      },

      /*
      *  返回上级页面
      * */
      prev() {
        this.$router.go(-1);
      },
      /*
      * 进行流量数据的获取
      *
      * */
      handleFlowChartQuery(hostDetails) {
        let type = hostDetails.type;
        if (hostDetails.type === 'ZBX' || hostDetails.type === 'ZBX不可用' ){
          type = 1;
        } else if (hostDetails.type === 'SNMP' || hostDetails.type === 'SNMP不可用') {
          type = 2;
        } else{
          type = 3;
        }

        let promise;
        // 代表需要请求的是SNMP数据
        if (Boolean(hostDetails.itemName)){
          promise = axios.post('/monitor/get_net_of_snmp_by_name_new.action', {
            itemName: hostDetails.itemName,
            hostId: hostDetails.hostId
          });
        } else {
          promise = axios.post('/monitor/get_net_by_host_id_new.action', {
            type: type,
            hostId: hostDetails.hostId
          });
        }
        // 返回处理后的promise对象，即字符串形式
        return new Promise( (resolve, reject) => {
          promise.then( response => {
            resolve(response.data.content.result);
          }).catch(err => {
            reject(err);
          })
        } );
      },
      /*
      * @description: 创建echart折线图
      * @params: chartData 流量图数据 num 流量图创建次序
      * */
      async drawLine(chartData, num) {
        // 基于准备好的dom，初始化echarts实例
        let myChart, query_result, maxFlow;
        let _this = this;
        myChart = this.$echarts.init(document.getElementById(chartData.name));
        // console.log(chartData);
        maxFlow = chartData.data[0].value;
        // 遍历找出流量图中的最大数据，进行动态设置流量图上限
        for (let i = 1; i < chartData.data.length; i++) {
          if (chartData.data[i].value > maxFlow){
            maxFlow = chartData.data[i].value;
          }
        }

        let option = {
          title: {
            text: chartData.name,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#283b56'
              }
            }
          },
          toolbox: {
            show: true,
            feature: {
              dataView: {readOnly: false},
              restore: {},
              saveAsImage: {}
            }
          },
          dataZoom: {
            show: false,
            start: 0,
            end: 100
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: true,
              data: (function () {
                var now = new Date();
                var res = [];
                var len = 10;
                while (len--) {
                  res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''));
                  now = new Date(now - 180000);
                }
                return res;
              })()
            }
          ],
          yAxis: [
            {
              type: 'value',
              scale: true,
              name: 'bps',
              // max: parseInt(maxFlow) + 5000000, // 极其健壮！
              //动态改变当前y轴的最大值和最小值
              max:function (value){
                return value.max
              },
              min:function (value){
                return value.min
              },
              boundaryGap: [0.2, 0.2]
            },
          ],
          series: [
            {
              name: '实时流量值',
              type: 'line',
              data: (function () {
                let res = [];
                // if (chartData.data.length < 10){
                //   let originLength = chartData.data.length;
                //   let lastVal = chartData.data[originLength].value;
                //   chartData.data.length = 10;
                //   for (let i = originLength + 1; i < chartData.data.length; i++) {
                //     chartData.data[originLength]["value"] = lastVal;
                //   }
                // }
                for (let i = 0; i < chartData.data.length; i++) {
                  res.push(chartData.data[i].value);
                }
                return res;
              })()
            }
          ]
        };
        myChart.setOption(option, true);
        // 每隔五秒绘制图表
        this.timers[num] = setInterval(async function () {

          // let new_query_result = await _this.handleFlowChartQuery(_this.transfer_data);
          // let result = new_query_result.datalist[num].data[new_query_result.datalist[num].data.length - 1];
          // console.log(result)
          // let new_query_result = await _this.sentNetItemAsyncRequest(_this.itemlist);
          // console.log('_this.itemlist',_this.itemlist);
          // console.log(new_query_result);


          let new_query_result = _this.new_data;
          let result;
          for (let i = 0; i < new_query_result.length; i++) {
            if(new_query_result[i].itemid == _this.itemlist[num]){
              result = new_query_result[i];
            }
          }
          // console.log(result)
          var axisData = (new Date()).toLocaleTimeString().replace(/^\D*/, '');
          var data1 = option.series[0].data;
          // console.log(data1)
          if (data1.length > 10){
            data1.shift(); // 删除数组头部元素
          }
          data1.push(result);

          if (result > maxFlow) {
            maxFlow = result;
          }

          option.xAxis[0].data.shift();
          option.xAxis[0].data.push(axisData);

          myChart.setOption(option, true);
        }, 5000);
      },
      setAsynInterval(){

          this.sentNetItemAsyncRequest(this.itemlist).then(data => {
              this.new_data = data
              console.log('promisedata',data);
              console.log('this.new_data',this.new_data);
          })
      },

      sentNetItemAsyncRequest(val){
        let promise;
        promise = axios.post('/monitor/get_new_net_data_by_itemid.action',{itemlist:val});
        // 返回处理后的promise对象，即字符串形式
        return new Promise( (resolve, reject) => {
          promise.then( response => {
            resolve(response.data.content.result);
          }).catch(err => {
            reject(err);
          })
        } );
      },
      resetDelayAs(val){
        axios.post('/monitor/resetDelayTime.action',{hostid:val})
      }
    },
    // 离开页面时，遍历销毁timers对象
    destroyed() {
      for (let i = 0; i < this.timers.length; i++) {
        clearInterval(this.timers[i]);
      }
      this.timers.length = 0;
      // this.resetDelayAs(this.hostid)
      clearInterval(this.current_timer)
    }
  }
</script>

<style scoped>
  .detailedflow_main {
    padding: 10px;
    height: 92vh;
    width: 100%;
    margin-top: 60px;
  }
  .detailedflow_content{
    margin-top: 0;
    width: 100%;
    height: 97%;
    overflow-y:auto;
    overflow-x: hidden;
  }
</style>
